﻿using Commission.Models;
using Commission.ViewModels;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace Commission.DAL
{
    public class ProductRepository : IDisposable
    {
        private SchoolContext context;

        public ProductRepository(SchoolContext context)
        {
            this.context = context;
        }

        public IEnumerable<Product> GetProducts()
        {
            return context.Products.Include(x => x.Unit);
        }

        public IEnumerable<Trading> GetTradings() 
        {
            return context.Tradings
                .Include(x => x.Customer)
                .Include(x => x.Product);
        }

        public Product GetProductByID(int? id)
        {
            return context.Products
                .Include(c => c.Unit)
                .Where(s => s.ProductId == id).FirstOrDefault<Product>();
        }

        public void InsertProduct(Product product)
        {
            

            context.Products.Add(product);
        }

        public void DeleteProduct(int productID)
        {
            Product product = context.Products.Find(productID);
            context.Products.Remove(product);
        }
        
        public void UpdateProduct(Product product)
        {
            context.Entry(product).State = EntityState.Modified;
        }

        public void OrderProduct(IList<Product> products, Customer login)
        {
            Trading trading = null;
            DateTime now = DateTime.Now;
            decimal amount = 0;

            foreach (var product in products)
            {
                if (product.Quantity == 0) continue;

                amount += product.Quantity * product.Price;
            }

            TransactionHistory trans = new TransactionHistory()
            {
                CustomerID = (int)login.CustomerID,
                AccountType = AccountType.Order,
                AccountDate = now,
                Amount = -amount,
                ProductAmount = decimal.Zero,
                Description = "Mua hàng",
                CreatedUserId = login.CustomerID,
                CreatedAt = now,
                UpdatedUserId = login.CustomerID,
                UpdatedAt = now,
            };
            context.TransactionHistories.Add(trans);
            context.SaveChanges();

            foreach (var product in products)
            {
                if (product.Quantity == 0) continue;

                trading = new Trading
                {
                    CustomerId = login.CustomerID,
                    ProductId = product.ProductId,
                    Quantity = product.Quantity,
                    Amount = product.Amount,
                    TradeDate = now,
                    TradeStatus = TradeStatus.Paid,
                    TransactionHistoryId = trans.ID,
                    CreatedAt = now,
                    CreatedUserId = login.CustomerID,
                    UpdatedAt = now,
                    UpdatedUserId = login.CustomerID
                };
                context.Tradings.Add(trading);
            }

            //login.ValidDate = DateTime.Now.AddDays(login.CustomerType.ValidDays);
            //context.Entry(login).State = EntityState.Modified;
        }

        public Customer GetCustomerByUserName(string userName)
        {
            return context.Customers
                .Where(s => s.UserName.Equals(userName))
                .FirstOrDefault<Customer>();
        }

        public void Save()
        {
            context.SaveChanges();
        }

        public IEnumerable<Unit> GetUnits()
        {
            return context.Units;
        }

        public IEnumerable<FileUpload> GetFileUploads()
        {
            return context.FileUploads;
        }

        public void InsertFileUpload(FileUpload fileUpload)
        {
            context.FileUploads.Add(fileUpload);
        }

        public FileUpload FileUploadByName(string fileName)
        {
            FileUpload fileUpload = context.FileUploads
                .Where(x => x.FileName.Equals(fileName))
                .FirstOrDefault<FileUpload>();

            return fileUpload;
        }

        public decimal GetTotalAmount80(int customerID)
        {
            var query = "SELECT Sum(Amount) AS TotalAmount"
                + " FROM TransactionHistory"
                + " WHERE CustomerID = @CustomerID"
                + " GROUP BY CustomerID";
            SqlParameter param1 = new SqlParameter("CustomerID", customerID);

            decimal amount = context.Database.SqlQuery<decimal>(
                    query, param1).FirstOrDefault();

            return amount;
        }

        public Trading GetTradingById(int tradingId)
        {
            return context.Tradings
                .Where(s => s.TradingId == tradingId)
                .FirstOrDefault<Trading>();
        }

        public void UpdateTrading(Trading trading)
        {
            context.Entry(trading).State = EntityState.Modified;
        }

        private bool disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    context.Dispose();
                }
            }
            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}